<template>
  <pageHeader :title="title" :breadCrumb="breadCrumb" showBack>
    <template #footer>
      <a-space style="margin-right: 20px">
        <a-button type="primary" @click="confirm"> 确认提交 </a-button>
      </a-space>
    </template>
    <div>
      <div class="main">
        <!-- <div class="title">
          <div class="icon"></div>
          <p>成品基本信息</p>
        </div> -->
        <TitleBox title="成品基本信息"></TitleBox>
        <div class="table">
          <a-table
            :scroll="{ x: 2000 }"
            :data="finishProductData"
            :pagination="false"
          >
            <template #columns>
              <a-table-column :width="80" align="center">
                <template #title> 序号 </template>
                <template #tr> </template>
                <template #cell="{ rowIndex }">
                  <div style="position: relative">
                    <div>{{ rowIndex + 1 }}</div>
                  </div>
                </template>
              </a-table-column>
              <a-table-column
                title="计划编号"
                :width="100"
                data-index="planCode"
                align="center"
              >
              </a-table-column>
              <a-table-column
                title="产品编码"
                :width="100"
                data-index="productNumber"
                align="center"
              ></a-table-column>
              <a-table-column
                title="产品名称"
                :width="100"
                data-index="productName"
                align="center"
              ></a-table-column>
              <a-table-column
                title="物料名称"
                :width="100"
                data-index="productName"
                align="center"
              ></a-table-column>
              <a-table-column
                title="规格型号"
                :width="100"
                data-index="spec"
                align="center"
              ></a-table-column>
              <a-table-column
                title="可领料数量"
                :width="100"
                data-index="canPickAmount"
                align="center"
              ></a-table-column>
              <a-table-column
                title="工单数量"
                :width="100"
                data-index="workOrderAmount"
                align="center"
              ></a-table-column>

              <a-table-column
                :title="Dayjs(nowDate).format('YYYY 年 MM 月')"
                align="left"
              >
                <a-table-column
                  v-for="(item, index) in dayList"
                  :key="index"
                  :width="80"
                  align="center"
                  :title="item.toDate().getDate() + '号'"
                >
                  <template #title>
                    <div>{{ item.toDate().getDate() + '号' }}</div>
                    <div>{{
                      ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][
                        item.day()
                      ]
                    }}</div>
                  </template>
                  <template #cell="{ record }">
                    {{ getNumber(item, record.data || []) }}
                  </template>
                </a-table-column>
              </a-table-column>
              <a-table-column
                fixed="right"
                title="领料数量"
                :width="100"
                align="center"
                ><template #cell="{ record }">
                  <a-input-number
                    :min="1"
                    v-model="setAmount"
                    :error="isError"
                    :max="record.canPickAmount"
                    @change="setAmountFun"
                /></template>
              </a-table-column>
            </template>
          </a-table>
        </div>
        <!-- <div class="title">
          <div class="icon"></div>
          <p>组件需求明细</p>
        </div> -->
        <TitleBox title="组件需求明细"></TitleBox>
        <div class="table">
          <a-table
            row-key="id"
            :scroll="{
              x: '100%',
              y: globalParameters.windowHeight - 300,
            }"
            :bordered="{ wrapper: true, cell: true }"
            :data="moduleData.data"
            v-model:selected-keys="selectedKeys"
            :row-selection="rowSelection"
            @select="onSelect"
            @select-all="onSelectAll"
            :pagination="false"
          >
            <template #columns>
              <a-table-column :width="80" align="center">
                <template #title> 序号 </template>
                <template #tr> </template>
                <template #cell="{ rowIndex }">
                  <div style="position: relative">
                    <div>{{ rowIndex + 1 }}</div>
                  </div>
                </template>
              </a-table-column>
              <a-table-column
                title="工序名称"
                :width="100"
                data-index="name"
                align="center"
              >
              </a-table-column>
              <a-table-column
                title="生产方式"
                :width="100"
                data-index="productionMethod"
                align="center"
              ></a-table-column>
              <a-table-column
                title="生产类型"
                :width="100"
                data-index="processType"
                align="center"
              ></a-table-column>
              <a-table-column
                title="是否报工"
                :width="100"
                data-index="productName"
                align="center"
                ><template #cell="{ record }">{{
                  record.isReportingWork === 0 ? '否' : '是'
                }}</template></a-table-column
              >
            </template>
          </a-table>
        </div>
        <!-- <div class="title">
          <div class="icon"></div>
          <a-space :size="40">
            <p>物料明细</p>
            <div>

            </div>
          </a-space>
        </div> -->
        <TitleBox title="物料明细"
          ><template #buts>
            <a-button type="primary" @click="addTd">添加</a-button
            ><a-button type="primary" @click="resetting">重置</a-button>
          </template></TitleBox
        >

        <div class="table">
          <a-table
            :scroll="{
              x: '100%',
              y: globalParameters.windowHeight - 300,
            }"
            :data="productDataLack.data"
            :pagination="false"
          >
            <template #columns>
              <a-table-column :width="80" align="center">
                <template #title> 序号 </template>
                <template #tr> </template>
                <template #cell="{ rowIndex }">
                  <div style="position: relative">
                    <div>{{ rowIndex + 1 }}</div>
                  </div>
                </template>
              </a-table-column>
              <a-table-column
                title="物料编码"
                :width="150"
                data-index="number"
                align="center"
              >
              </a-table-column>
              <a-table-column
                title="物料名称"
                :width="150"
                data-index="name"
                align="center"
              ></a-table-column>
              <a-table-column
                title="规格型号"
                :width="150"
                data-index="spec"
                align="center"
              ></a-table-column>
              <a-table-column
                title="基本单位"
                :width="150"
                data-index="basicName"
                align="center"
              ></a-table-column>
              <a-table-column
                title="物料分类"
                :width="150"
                data-index="materialName"
                align="center"
              ></a-table-column>
              <a-table-column
                title="需求数量"
                :width="150"
                data-index="demandAmount"
                align="center"
                ><template #cell="{ record }">
                  {{ record.demandAmount || '-' }}</template
                ></a-table-column
              >

              <a-table-column
                title="空闲库存数量"
                :width="150"
                data-index="freeStock"
                align="center"
              ></a-table-column>
              <a-table-column
                title="标准用量"
                :width="150"
                data-index="dosage"
                align="center"
                ><template #cell="{ record }">
                  {{ record.dosage || '-' }}</template
                ></a-table-column
              >
              <a-table-column
                title="推荐领料数量"
                :width="200"
                data-index="basicName"
                align="center"
                fixed="right"
                ><template #cell="{ record }">
                  <a-input-number
                    :min="1"
                    v-model="record.amount"
                    :max="record.canPickAmount" /></template
              ></a-table-column>
              <!-- <a-table-column
              title="操作"
              :width="300"
              align="center"
              fixed="right"
              ><template #cell="{ rowIndex }">
                <a-button type="text" status="danger" @click="delItem(rowIndex)"
                  >删除</a-button
                ></template
              ></a-table-column
            > -->
            </template>
          </a-table>
        </div>
      </div>
    </div>
  </pageHeader>

  <a-modal
    v-if="modelVisible"
    :width="800"
    v-model:visible="modelVisible"
    @ok="handleOk"
    :mask-closable="false"
  >
    <template #title> 物料产品选择 </template>
    <div class="container">
      <div class="content">
        <tableTurn :table-data="getMaterialData" ref="tableRef" :args="args">
          <a-table-column :width="80" align="center">
            <template #title> 序号 </template>
            <template #cell="{ rowIndex }">
              {{ rowIndex + 1 }}
            </template>
          </a-table-column>
          <a-table-column
            align="center"
            :width="200"
            title="物料编码"
            data-index="number"
          >
          </a-table-column>
          <a-table-column
            align="center"
            :width="150"
            title="物料名称"
            data-index="name"
          >
          </a-table-column>

          <a-table-column
            align="center"
            :width="150"
            title="规格型号"
            data-index="spec"
          >
          </a-table-column>
          <a-table-column
            data-index="basicName"
            align="center"
            :width="100"
            title="基本单位"
          >
          </a-table-column>

          <a-table-column
            align="center"
            :width="200"
            title="备注"
            data-index="remark"
          >
          </a-table-column>
        </tableTurn>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
  import { reactive, ref, computed, watch, watchEffect } from 'vue';
  // import materielModal from '@/components/materielModal/index.vue';
  import pageHeader from '@/components/page-header/index.vue';
  import { useRouter, useRoute } from 'vue-router';
  import { useProduceStore } from '@/store';
  import { GetProducePlanDetail } from '@/api/produce-management/OrderPlanning/index';
  import {
    GetProductProcessRoutePage,
    GetProductBom,
  } from '@/api/FactoryModeling/index';
  import { Message } from '@arco-design/web-vue';
  import { cloneDeep } from 'lodash';
  import { GetOverviewList } from '@/api/inventory-management/inventory-query/inventory-qverview';
  import Dayjs from 'dayjs';
  import { useGlobalParametersStore, useBuyStore } from '@/store';
  import tabItemVue from '@/components/tab-bar/tab-item.vue';

  const globalParameters = useGlobalParametersStore();
  const emergencyLevel = [
    { id: 1, value: '一般', color: '#009933' },
    { id: 2, value: '紧急', color: '#409eff' },
    { id: 3, value: '加急', color: '#ff8000' },
    { id: 4, value: '特急', color: '#ff0000' },
  ];
  const productSelectedKeys = ref([]);
  const setAmount = ref();
  const finishProductData = ref([]);
  const selectedKeys = ref([]);
  const modelVisible = ref(false);
  const Store = useProduceStore();
  const router = useRouter();
  const isError = ref(false);
  const route = useRoute();
  const bomData = ref();
  const id = ref(Number(route.query.id));
  const canPickAmount = ref(Number(route.query.canPickAmount));
  const state = ref(Number(route.query.state));
  const title: string = '创建生产领料详情页';
  const breadCrumb: string[] = ['生产管理', '生产计划', '创建生产领料详情页'];
  let tableRef = ref();
  const moduleData = reactive<any>({ data: [] });
  const productDataLack: any = reactive({ data: [] });
  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  });

  let nowDate = ref(new Date());
  let dayList = computed(() => {
    // let { type } = searchForm;
    let list = [];
    let getNowDate = Dayjs(nowDate.value);
    // if (type === 2) {
    let day = getNowDate.day();
    let startDate = day
      ? getNowDate.subtract(day, 'd')
      : getNowDate.add(day, 'd');
    for (let i = 0; i < 7; i += 1) {
      list.push(startDate.add(i + 1, 'd'));
    }
    return list;
  });
  let getNumber = (dateItem: any, list: any[]) => {
    return list.find(({ date }) => {
      if (!date) return false;
      return dateItem.isSame(Dayjs(date), 'day');
    })?.number;
  };

  const init = async () => {
    try {
      const res: any = await GetProducePlanDetail({ id: id.value });

      const msg = await GetProductProcessRoutePage({
        productId: res.productId,
        history: 1,
        page: 1,
        size: -1,
      });
      bomData.value = await GetProductBom({
        id: res.bomId,
      });

      finishProductData.value.push({ ...res });
      // if (!state.value && !canPickAmount.value) {
      //   finishProductData.value[0].canPickAmount =
      //     finishProductData.value[0].workOrderAmount;
      // } else if (!state.value && canPickAmount.value) {
      finishProductData.value[0].canPickAmount = canPickAmount.value;
      // }

      moduleData.data = msg.content[0].groupData;
    } catch (error) {
      console.log(error);
      Message.error('服务出错');
    }
  };

  init();

  // const selectedList = ref();
  // 选择数据事件
  const onSelect = (rowKeys: any, rowKey: any, record: any) => {
    const newArr: any = [];
    productDataLack.data = [];
    rowKeys.forEach((ele: any) => {
      moduleData.data.forEach((item: any) => {
        if (ele === item.id)
          bomData.value.productBomDetail.forEach((element: any) => {
            const index = element.productGroupData.findIndex(
              (val) => val.productGroupId === ele
            );
            if (index > -1) {
              newArr.push({
                ...element.productBomDetail.management,
                dosage: element.productGroupData[index].dosage,
              });
            }
          });
      });
    });
    newArr.forEach((ele: any) => {
      const index = productDataLack.data.findIndex((i) => ele.name === i.name);
      if (index === -1) {
        productDataLack.data.push({ ...ele });
      } else {
        productDataLack.data[index].dosage += ele.dosage;
      }
    });

    productDataLack.data.forEach(async (item: any) => {
      const res = await GetOverviewList({
        number: item.number,
        page: 1,
        size: 99999,
      });
      Object.assign(item, res.content[0]);
    });

    setAmount.value = 0;
  };

  // 全选按钮
  const onSelectAll = async (checked: boolean) => {
    if (checked) {
      productDataLack.data = [];
      let newArr: any = [];
      moduleData.data.forEach((item: any) => {
        bomData.value.productBomDetail.forEach((element: any) => {
          const index = element.productGroupData.findIndex(
            (val: any) => val.productGroupId === item.id
          );
          if (index > -1) {
            newArr.push({
              ...element.productBomDetail.management,
              dosage: element.productGroupData[index].dosage,
            });
          }
        });
      });

      newArr.forEach((ele: any) => {
        const index = productDataLack.data.findIndex(
          (i: any) => ele.name === i.name
        );
        if (index === -1) {
          productDataLack.data.push({ ...ele });
        } else {
          productDataLack.data[index].dosage += ele.dosage;
        }
      });

      productDataLack.data.forEach(async (item: any) => {
        const res = await GetOverviewList({
          number: item.number,
          page: 1,
          size: 99999,
        });
        Object.assign(item, res.content[0]);
      });

      setAmount.value = 0;
    } else {
      productDataLack.data = [];
      setAmount.value = 0;
    }
  };

  const setAmountFun = (val: any) => {
    if (setAmount.value) isError.value = false;
    productDataLack.data.forEach((item: any) => {
      if (!item.dosage) return;
      item.demandAmount = val * item.dosage;
    });
  };

  watch(setAmount.value, (val) => {
    setAmountFun(val);
  });

  // 选择器配置
  const args = reactive({
    rowSelection: {
      type: 'checkbox',
      showCheckedAll: true,
      onlyCurrent: false,
    },
  });

  const confirm = () => {
    if (!setAmount.value) {
      isError.value = true;
      Message.error('领料数量不能为空！');
      return;
    }
    if (finishProductData.value[0].canPickAmount === setAmount.value) {
      finishProductData.value[0].finish = true;
    }
    Store.PickingData = {
      amount: setAmount.value,
      ...finishProductData.value[0],
      product: productDataLack.data,
    };
    router.push({ name: 'AddProduceOutbound' });
  };

  const addTd = () => {
    modelVisible.value = true;
    tableRef.value.selectedKeys = [];
    tableRef.value.selectedList = [];
  };

  let numberVal = ref(''); // 物料编码搜索值
  let nameVal = ref(''); // 物料编码搜索值

  // 获取物料列表数据
  const getMaterialData = async (pageData?: any) => {
    try {
      const data: any = {};
      const res = await GetOverviewList({
        ...pageData,
        ...data,
      });
      res.content.forEach((item: any) => {
        productDataLack.data.forEach((ele: any) => {
          if (item.number === ele.managementNumber) {
            item.disabled = true;
          }
        });
      });
      return Promise.resolve(res);
    } catch (error: unknown) {
      console.log(error);
    }
  };

  const MaterialData = ref<any>([]);
  const handleOk = () => {
    tableRef.value.selectedList.forEach((element) => {
      const index = productDataLack.data.findIndex(
        (i) => i.managementName === element.name
      );
      if (index === -1)
        MaterialData.value.push({
          managementName: element.name,
          managementNumber: element.number,
          freeAmount: element.freeStock,
          ...element,
        });
    });
  };

  watchEffect(() => {
    if (MaterialData.value && productDataLack.data) {
      productDataLack.data = productDataLack.data.concat(MaterialData.value);
    }
  });

  const resetting = () => {
    selectedKeys.value = [];
    productDataLack.data = [];
    MaterialData.value = [];
    setAmount.value = null;
  };
  // const delTd = () => {
  //   productSelectedKeys.value.forEach((item) => {
  //     const index = productDataLack.data.findIndex((i) => i.id === item);
  //     productDataLack.data.splice(index, 1);
  //   });
  // };

  const delItem = (index: any) => {
    productDataLack.data.splice(index, 1);
  };
</script>

<style lang="less" scoped>
  .main {
    width: 100%;
    padding: 20px;
    margin-bottom: 150px;
    .title {
      display: flex;
      align-items: center;
      margin-bottom: 20px;
      .icon {
        background-color: #3d7eff;
        width: 5px;
        height: 20px;
        border-radius: 5px;
        margin-right: 10px;
      }
      p {
        font-size: 16px;
        padding: 0;
        margin: 0;
      }
    }
    .table {
      width: 100%;
      padding: 20px;
      margin-bottom: 20px;
      border-radius: 5px;
      box-shadow: 0 0 5px #d7cece;
    }
  }
  .foot {
    padding-top: 10px;
    margin-top: 10px;
    border-top: 1px solid #e4e4e4;
    display: flex;
    justify-content: end;
  }
  .status {
    display: flex;
    justify-content: center;
    align-items: center;
    // background-color: #ff4a4a;
    color: #ff4a4a;
    p {
      width: 12px;
      height: 12px;
      border-radius: 50%;
      margin-right: 10px;
      background-color: #ff4a4a;
      box-shadow: 0px 0px 5px;
    }
  }
  .lack {
    // background-color: #009933;
    color: #009933;
    p {
      background-color: #009933;
    }
  }

  :deep(.arco-table-tr) {
    height: 40px;
  }
  :deep(.arco-table-th) {
    font-weight: bold;
    // font-size: 13px;
  }
</style>
